package com.xuedongzhilian.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.xuedongzhilian.dto.UserDTO;
import org.springframework.web.servlet.HandlerInterceptor;
import com.xuedongzhilian.entity.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;

/**
 * 第二个拦截器
 * 登录校验拦截器
 * 1.判断是否需要拦截（ThreadLocal中是否有用户)
 * 2.有用户，则放行
 * 3.没有用户，则拦截，返回401状态码
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录请求信息
        String requestURI = request.getRequestURI();
        log.info("LoginInterceptor intercepting request: {}", requestURI);
        
        // 检查是否应该放行此路径
        String[] excludePaths = {
            "/shop/**",
            "/voucher/**", 
            "/shop-type/**",
            "/upload/**",
            "/blog/hot",
            "/user/code",
            "/user/login",
            "/user/manage/wechat/login"
        };
        
        boolean shouldExclude = false;
        for (String excludePath : excludePaths) {
            if (excludePath.endsWith("/**")) {
                String prefix = excludePath.substring(0, excludePath.length() - 3);
                if (requestURI.startsWith(prefix)) {
                    shouldExclude = true;
                    break;
                }
            } else if (requestURI.equals(excludePath)) {
                shouldExclude = true;
                break;
            }
        }
        
        if (shouldExclude) {
            log.info("LoginInterceptor excluding request: {}", requestURI);
            return true; // 放行
        }
        
        //1.判断是否需要拦截（ThreadLocal中是否有用户)
        if(UserHolder.getUser()==null){
            log.info("User not logged in, returning 401 for request: {}", requestURI);
            //没有，需要拦截，设置状态码
            response.setStatus(401);
            return false;
        }
        log.info("User logged in, allowing request: {}", requestURI);
        return true;
    }
}